﻿using System.Net;
using System.Text;

using BodaNetCommunications.Cores;
using BodaNetCommunications.Utilities.Results;

namespace BodaNetCommunications.TcpComs
{
    public class TcpCommService : CommReadWrite, ITcpCommService
    {
        public ConnectionOptions Options { get; private set; }

        public TcpClient Tcp { get; private set; }

        public bool IsConnected => Tcp != null && Tcp.IsConnected;

        public TcpCommService()
        {

        }

        public void Dispose()
        {
            this.Disconnect();
        }
        public BodaResult Connect(ConnectionOptions connectionOptions)
        {
            BodaResult bodaResult = new BodaResult();
            Options = connectionOptions;

            if (string.IsNullOrEmpty(Options.Ip) || false == IPAddress.TryParse(Options.Ip, out _))
            {
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"Ip[{Options.Ip}]为空或者格式不正确";
                return bodaResult;
            }

            if (Options.Port < 0 || Options.Port > 65535)
            {
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"Port[{Options.Port}]不正确";
                return bodaResult;
            }

            if (IsConnected)
            {
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"Tcp【{Options.Ip}:{Options.Port}】的连接已经在线，不需要重复连接";
                return bodaResult;
            }

            Tcp = new TcpClient();
            return Tcp.Connect(Options);
        }

        public void Disconnect()
        {
            Tcp?.Disconnect();
        }

        public override Task<BodaResult> SendMsgAsync(string msg, int timeout = 1500)
        {
            var messageBytes = Encoding.UTF8.GetBytes(msg);
            var res = SendMsgc(messageBytes, timeout);
            return Task.FromResult(res);
        }

        public BodaResult SendMsgc(byte[] bytes, int timeout = 1500)
        {
            return Tcp.SendMsgc(bytes, timeout);
        }

        public BodaResult<byte> ReceiveMsg(int timeout = 2000, int bytesLen = 1024)
        {
            return Tcp.ReceiveMsg(timeout, bytesLen);
        }

        public override Task<BodaResult<string>> ReceiveMsgAsync(int timeout = 2000, int bytesLen = 1024, CancellationToken cancellationToken = default)
        {
            BodaResult<string> bodaResult = new BodaResult<string>();
            var res = Tcp.ReceiveMsg(timeout, bytesLen);
            bodaResult.IsSuccess = res.IsSuccess;
            if (res.IsSuccess)
            {
                var response = Encoding.UTF8.GetString(res.Datas.ToArray(), 0, res.Datas.Count);
                bodaResult.Content = response;
            }
            else
            {
                bodaResult.Message = res.Message;
            }
            return Task.FromResult(bodaResult);
        }
    }
}
